package hz.mobileproject.pda.ui.frgment.second;

import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.activity.CaptureActivity;
import com.hejunlin.superindicatorlibray.CircleIndicator;
import com.hejunlin.superindicatorlibray.LoopViewPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.broadcast.HandleBroadcast;
import hz.mobileproject.pda.broadcast.IShowBarcodeStr;
import hz.mobileproject.pda.callroll.activity.AddCallRecordCallActivity;
import hz.mobileproject.pda.entity.request.Request_addAlarm;
import hz.mobileproject.pda.entity.request.Request_data;
import hz.mobileproject.pda.entity.request.Request_loadPersioneInfo;
import hz.mobileproject.pda.entity.response.Response_alarm_type_data;
import hz.mobileproject.pda.entity.response.Rp_loadPrisonerInfo;
import hz.mobileproject.pda.firesafety.activity.FireSearchActivity;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.model.attendancemanager.activity.AttendanceMainActivity;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.push.mqtt.MqttClientMgr;
import hz.mobileproject.pda.toolsmanager.activity.ToolsMainActivity;
import hz.mobileproject.pda.ui.activity.EduTalkActivity;
import hz.mobileproject.pda.ui.activity.FamilyPhoneActivity;
import hz.mobileproject.pda.ui.activity.KeyPlaceActivity;
import hz.mobileproject.pda.ui.activity.MeetRecordingActivity;
import hz.mobileproject.pda.ui.activity.work.AssetsTakingActivity;
import hz.mobileproject.pda.ui.activity.work.LocalDisposeActivity;
import hz.mobileproject.pda.ui.activity.work.OddPostActivity;
import hz.mobileproject.pda.ui.adapter.ChatAdapter;
import hz.mobileproject.pda.ui.adapter.PicAdapter;
import hz.mobileproject.pda.ui.adapter.WorkAdapter;
import hz.mobileproject.pda.ui.base.BaseMainFragment;
import hz.mobileproject.pda.ui.view.DividerGridItemDecoration;
import hz.mobileproject.pda.ui.view.LoadingDialog;
import hz.mobileproject.pda.utils.Base64;
import hz.mobileproject.pda.utils.CommonUtil;
import hz.mobileproject.pda.utils.HttpRqUtils;

import static android.content.Context.WIFI_SERVICE;


/**
 * Created by YoKeyword on 16/6/30.
 */
public class WorkFragment extends BaseMainFragment implements IShowBarcodeStr {


    public final String Project_Name = Constance.PROJECT_NAME;

    private RecyclerView mRecy;

    private boolean mInAtTop = true;
    private int mScrollTotal;

    private ChatAdapter mAdapter;
    private RecyclerView mRecyclerView;
    private WorkAdapter mWorkAdapter;
    private GridLayoutManager mGridLayoutManager;
    private AlertDialog mAlertDialog;
    private SPUtils mSPUtils;
    private WifiManager mWifiManager;
    private Gson mGson;

    private HandleBroadcast mHandleBroadcast;
    private SoundPool mSoundpool;
    private int mSoundid;
    private static final int SCAN_PRISONOR_REQUEST_CODE = 0x333;

    private RelativeLayout rlayout1;
    private List<Response_alarm_type_data> mResponse_alarm_type_dataList;
    private LoadingDialog mLoadingDialog;

    private String alarmPrisonerName = "";
    private String alarmPrisonId = "";
    private AlertDialog mAlertDialog1;
    private Response_alarm_type_data mResponse_alarm_type_data;

    public static WorkFragment newInstance() {

        Bundle args = new Bundle();

        WorkFragment fragment = new WorkFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_work_second, container, false);
        initView(view);
        initListener();
        return view;


    }


    /**
     * 打开扫描
     */
    private void openScan(int requestCode) {
        mLoadingDialog = new LoadingDialog(getContext());
        if (Constance.isNeiMeng) {  //如果是演示版本则打开相机扫描
            //打开二维码扫描界面
            if (CommonUtil.isCameraCanUse()) {
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                startActivityForResult(intent, requestCode);
            } else {
                Toast.makeText(getContext(), "请打开此应用的摄像头权限！", Toast.LENGTH_SHORT).show();
            }
        } else {
            mHandleBroadcast = new HandleBroadcast(this, getContext());
            mSoundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
            mSoundid = mSoundpool.load("/etc/Scan_new.ogg", 1);
            mLoadingDialog.setMessage("请扫描疾病罪犯二维码").show();
        }
    }


    @Subscribe
    public void initView(View view) {
        mWifiManager = (WifiManager)getActivity().getApplicationContext().getSystemService(WIFI_SERVICE);
        mSPUtils = SPUtils.getInstance("app_login");
        mGson = new Gson();

        LoopViewPager viewpager = (LoopViewPager) view.findViewById(R.id.viewpager);
        CircleIndicator indicator = (CircleIndicator) view.findViewById(R.id.indicator);


        viewpager.setAdapter(new PicAdapter(getActivity()));
        viewpager.setLooperPic(true);
        indicator.setViewPager(viewpager);

        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        mWorkAdapter = new WorkAdapter(getActivity());

        mGridLayoutManager = new GridLayoutManager(getActivity(),3);

        mRecyclerView.setLayoutManager(mGridLayoutManager);

        mRecyclerView.addItemDecoration(new DividerGridItemDecoration(getContext(), 3));

        mRecyclerView.setAdapter(mWorkAdapter);
        EventBus.getDefault().register(this);

        rlayout1 = (RelativeLayout) view.findViewById(R.id.rlayout1);

    }
    private void initListener() {

        mWorkAdapter.setOnItemClickListener(new WorkAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                switch (position){
//                    case 0://电子巡警
//                        startActivity(new Intent(getActivity(), AddCallRecordCallActivity.class));
//                        break;
//                    case 1:
//                        startActivity(new Intent(getActivity() , ToolsMainActivity.class));
//                        break;
//                    case 2:   //现场处置
//
//                        startActivity(new Intent(getActivity(),LocalDisposeActivity.class));
//                        break;
//                    case 3:
//                        startActivity(new Intent(getActivity() , FireSearchActivity.class));
//                        break;
//                    case 4://重点部位巡查
//                        startActivity(new Intent(getActivity(), KeyPlaceActivity.class));
//                        break;
//                    case 5:
//                        startActivity(new Intent(getActivity(), OddPostActivity.class));
//                        break;
//                    case 6:
//                        startActivity(new Intent(getActivity(), EduTalkActivity.class));
//                        break;
//                    case 7:
//                        //请求加载报警类型接口
//                        getAlarmType();
//
//
//                        break;
//                    case 8://亲情电话
//                        startActivity(new Intent(getActivity() , FamilyPhoneActivity.class));
//                        break;
//                    case 9://会见录音
//                        startActivity(new Intent(getActivity() , MeetRecordingActivity.class));
//                        break;
//                    case 10://资产盘点
//                        startActivity(new Intent(getActivity() , AssetsTakingActivity.class));
//                        break;
//                    case 11://考勤管理
//                        startActivity(new Intent(getActivity() , AttendanceMainActivity.class));
//                        break;


                    //TODO 广西江宁监狱  只部署电子点名和教育谈话
                    case 0://电子巡警
                        startActivity(new Intent(getActivity(), AddCallRecordCallActivity.class));
                        break;
                    case 1:
                        startActivity(new Intent(getActivity(), EduTalkActivity.class));
                        break;
                }
            }
        });
    }

    private void getAlarmType() {
        Request_data data = new Request_data();
        data.setData(Base64.getBase64(""));
        String body_data=  mGson.toJson(data);
        //将body作为网络请求
        RequestParams params = new RequestParams(Constance.BASE_URL + "/"+ Project_Name + "/eventReport/loadOneKeyAlarmType");
        params.setBodyContent(body_data);
        x.http().post(params, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);

                //12月18日更改description为desc_array 字段
                mResponse_alarm_type_dataList = new Gson().fromJson(data,new TypeToken<List<Response_alarm_type_data>>(){}.getType());
                //类别名称
                final String[] nameStrs = new String[mResponse_alarm_type_dataList.size()];
                //描述
                final String[] desStrs = new String[mResponse_alarm_type_dataList.size()];

                for(int i = 0; i < mResponse_alarm_type_dataList.size(); i++) {
                    nameStrs[i] = mResponse_alarm_type_dataList.get(i).getName();
                    List<Response_alarm_type_data.DescBean> descBeanList = mResponse_alarm_type_dataList.get(i).getDesc_array();
                    String str = "";
                    for(int j = 0; j < descBeanList.size();j++) {
                        str += descBeanList.get(j).getFlow_name() + "\n";
                    }
                    desStrs[i] = str;
                }

                //弹出AlertDialog
                AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
                dialog.setItems(nameStrs, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                        builder.setTitle(nameStrs[which]+"报警处置说明");
                        builder.setMessage(desStrs[which]);
                        builder.setPositiveButton("确认",null);
                        mAlertDialog1 = builder.create();
                        mAlertDialog1.setCancelable(false);
                        mResponse_alarm_type_data = mResponse_alarm_type_dataList.get(which);
                        //突发疾病
                        if("1".equals(mResponse_alarm_type_dataList.get(which).getId())) {
                            //弹出扫描条码界面， 扫描罪犯
                            LogUtils.e("点击突发疾病");
                            openScan(SCAN_PRISONOR_REQUEST_CODE);
                        }else {
                            mAlertDialog1.show();
                            alarmPrisonerName = "";
                            alarmPrisonId = "";
                            LogUtils.e("没有点击突发疾病");
                            addAlarm(mResponse_alarm_type_data);
                        }



                    }


                });
                //显示提示框
                dialog.show();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("连接服务器出错");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("连接服务器出错");
            }
        });
    }

    private void addAlarm(Response_alarm_type_data response_alarm_type_data) {
        //请求接口
        String cus_number = mSPUtils.getString("cusnumber");
        final String report_dept_id = mSPUtils.getString("department_id");
        String report_dept_name = mSPUtils.getString("department_name");
        String report_police_id = mSPUtils.getString("police_id");
        String report_police_name = mSPUtils.getString("police_name");
        //12月19日新加字段
        String alarm_type = response_alarm_type_data.getId();
        String alarm_type_name = response_alarm_type_data.getName();
        String mac = null;
        if(mWifiManager.isWifiEnabled()) {
            WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
            //获取被连接网络的mac地址
            mac = wifiInfo.getBSSID();
        }
        String report_time = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        LogUtils.e("疾病罪犯" + alarmPrisonerName + "----" + alarmPrisonId);
        Request_addAlarm request_addAlarm = new Request_addAlarm(cus_number,report_dept_id,report_dept_name,report_police_id,report_police_name,mac,report_time,alarm_type,alarm_type_name,alarmPrisonerName,alarmPrisonId, MqttClientMgr.CLIENT_ID);
        String json_request_addAlarm = mGson.toJson(request_addAlarm);
        String mrequest_data = json_request_addAlarm;
        LogUtils.e(mrequest_data);
        Request_data data = new Request_data();
        data.setData(Base64.getBase64(json_request_addAlarm));
        String body_data=  mGson.toJson(data);
        //将body作为网络请求
        RequestParams params = new RequestParams(Constance.BASE_URL + "/" + Project_Name + "/eventReport/addAlarm");
        params.setBodyContent(body_data);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.e(result);
                LogUtils.e(Base64.getBase64(result));
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if("0".equals(jsonObject.getString("rtnCode"))) {
                        ToastUtils.showLong("报警成功");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtils.e(ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);

    }





    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void updateText(String msg) {
        mSoundpool.play(mSoundid, 1, 1, 0, 0, 1);
        if(mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
        Request_loadPersioneInfo rq_lpi = new Request_loadPersioneInfo();
        rq_lpi.setCusNumber(SPUtils.getInstance("app_login").getString(Constance.SP_CUSNUMBER));
        rq_lpi.setPrisonerId(msg);
        //发送获取罪犯信息接口请求
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_LOAD_PRISONER_INFO, rq_lpi, prisonerInfoCallback);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(SCAN_PRISONOR_REQUEST_CODE == requestCode && resultCode == CaptureActivity.RESULT_CODE_QR_SCAN){
            Request_loadPersioneInfo rq_lpi = new Request_loadPersioneInfo();
            rq_lpi.setCusNumber(SPUtils.getInstance("app_login").getString(Constance.SP_CUSNUMBER));
            rq_lpi.setPrisonerId(data.getStringExtra(CaptureActivity.INTENT_EXTRA_KEY_QR_SCAN));
            //发送获取罪犯信息接口请求
            HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_LOAD_PRISONER_INFO, rq_lpi, prisonerInfoCallback);
        }
    }

    private CustomNetCallBack prisonerInfoCallback = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            Rp_loadPrisonerInfo loadPrisonerInfo = mGson.fromJson(data, Rp_loadPrisonerInfo.class);
            if (loadPrisonerInfo == null) {
                ToastUtils.showLong("罪犯信息为空");
                return;
            }
            if (mHandleBroadcast != null) {
                mHandleBroadcast.overBroadcastReceiver(getContext());
            }
            alarmPrisonerName = loadPrisonerInfo.getPrisoner_name();
            alarmPrisonId = loadPrisonerInfo.getPrisoner_id();
            mAlertDialog1.show();    //先扫描罪犯 然后弹出处置弹窗
            addAlarm(mResponse_alarm_type_data);
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取罪犯信息失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("获取罪犯信息失败");
            LogUtils.e(ex);
        }
    };


    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mHandleBroadcast != null) {
            mHandleBroadcast.overBroadcastReceiver(getContext());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
